<template>
  <a-row class="operator-wrapper">
    <!--操作列-->
    <a-col :span="12">
      <a-space>
        <template
          v-for="item in operators"
          :key="item.operators"
        >
          <a-button
            v-permission="[item.permission]"
            type="primary"
            size="medium"
            @click="$emit('operator',item.operator)"
          >
            <template #icon>
              <component :is="item.icon" />
            </template>
            {{ $t(item.name) }}
          </a-button>
        </template>
      </a-space>
    </a-col>
    <!--表格设置-->
    <a-col class="setting-wrapper" :span="12">
      <!--刷新-->
      <a-tooltip
        v-if="hasRefresh"
        :content="$t('table.actions.refresh')"
      >
        <div class="action-icon" @click="refresh">
          <icon-refresh size="18" />
        </div>
      </a-tooltip>
      <!--密度设置-->
      <a-dropdown
        v-if="density"
        @select="selectDensity"
      >
        <a-tooltip :content="$t('table.actions.density')">
          <div class="action-icon">
            <icon-line-height size="18" />
          </div>
        </a-tooltip>
        <template #content>
          <a-doption
            v-for="item in densityList"
            :key="item.value"
            :value="item.value"
            :class="{ active: item.value === size }"
          >
            <span>{{ item.name }}</span>
          </a-doption>
        </template>
      </a-dropdown>
      <!--列排序-->
      <a-tooltip
        v-if="columnSetting"
        :content="$t('table.actions.columnSetting')"
      >
        <a-popover
          trigger="click"
          position="br"
          @popup-visible-change="visibleChange"
        >
          <div class="action-icon">
            <icon-settings size="18" />
          </div>
          <template #content>
            <div id="tableSetting">
              <div
                v-for="(item, index) in showColumns"
                :key="item.dataIndex"
                class="setting"
              >
                <div style="margin-right: 4px; cursor: move">
                  <icon-drag-arrow />
                </div>
                <div>
                  <a-checkbox
                    v-model="item.checked"
                    @change="handleChange($event, item, index)"
                  >
                  </a-checkbox>
                </div>
                <div class="title">
                  {{ item.title === '#' ? '序列号' : item.title }}
                </div>
              </div>
            </div>
          </template>
        </a-popover>
      </a-tooltip>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
import { ref, nextTick, defineProps, watch, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import Sortable from 'sortablejs';
import cloneDeep from 'lodash/cloneDeep';
import { TableColumnData } from '@arco-design/web-vue/es/table/interface';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };

const props = defineProps({
  operators: {
    type: Array,
    default: () => {
      return [];
    }
  },
  columns: {
    type: Array,
    default: () => {
      return [];
    }
  },
  hasRefresh: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  density: {
    type: Boolean,
    default: () => {
      return true;
    }
  },
  columnSetting: {
    type: Boolean,
    default: () => {
      return true;
    }
  }
});

const emits = defineEmits(['refresh', 'density', 'column']);

const { t } = useI18n();

const size = ref<SizeProps>('medium');
const densityList = computed(() => [
  {
    name: t('table.size.mini'),
    value: 'mini'
  },
  {
    name: t('table.size.small'),
    value: 'small'
  },
  {
    name: t('table.size.medium'),
    value: 'medium'
  },
  {
    name: t('table.size.large'),
    value: 'large'
  }
]);

const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);


const refresh = () => {
  emits('refresh');
};

const selectDensity = (value: string | number | Record<string, any> | undefined, e: Event) => {
  size.value = value as SizeProps;
  emits('density', size.value);
};

const exchangeArray = (array: Array<any>, beforeIdx: number, newIdx: number, isDeep = false) => {
  const newArray = isDeep ? cloneDeep(array) : array;
  if (beforeIdx > -1 && newIdx > -1) {
    newArray.splice(beforeIdx, 1, newArray.splice(newIdx, 1, newArray[beforeIdx]).pop());
  }
  return newArray;
};

const visibleChange = (value: any) => {
  if (!value) {
    return;
  }
  nextTick(() => {
    const el = document.getElementById('tableSetting') as HTMLElement;
    const sortable = new Sortable(el, {
      onEnd(e: any) {
        const { oldIndex, newIndex } = e;
        exchangeArray(cloneColumns.value, oldIndex, newIndex);
        exchangeArray(showColumns.value, oldIndex, newIndex);
        emits('column', cloneColumns.value);
      }
    });
  });
};

const handleChange = (checked: boolean | (string | boolean | number)[], column: Column, index: number) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter((item) => item.dataIndex !== column.dataIndex);
  } else {
    cloneColumns.value.splice(index, 0, column);
  }
  emits('column', cloneColumns.value);
};

watch(
  () => props.columns,
  (value) => {
    cloneColumns.value = cloneDeep(value as Column[]);
    cloneColumns.value.forEach((item) => {
      item.checked = true;
    });
    showColumns.value = cloneDeep(cloneColumns.value);
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="less">

.operator-wrapper {
  margin-bottom: 16px;
}

.setting-wrapper {
  display: flex;
  align-items: center;
  justify-content: end
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>